import 'package:flutter/material.dart';
import 'package:flutter_form_builder/flutter_form_builder.dart';
import 'package:myapp/page/webview/index.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:http/http.dart' as http;

class Address extends StatefulWidget {
  const Address({super.key});

  @override
  State<Address> createState() => _Content();
}

class _Content extends State<Address> {
  final GlobalKey<FormBuilderState> _formKey = GlobalKey<FormBuilderState>();
  late final SharedPreferences _prefs;

  @override
  void initState() {
    init();
    super.initState();
  }

  // 给初始表单设置值
  void init() async {
    _prefs = await SharedPreferences.getInstance();
    String ip = _prefs.getString('ip') ?? '';
    String port = _prefs.getString('port') ?? '';
    WidgetsBinding.instance.addPostFrameCallback((_) {
      _formKey.currentState?.patchValue({'ip': ip, 'port': port});
    });
  }

  // 请求验证码
  void fetchData(ip, port) async {
    final response = await http.get(Uri.http('$ip:$port', '/prod-api/auth/code'));
    debugPrint('response-------------$response');
  }

  void showAlert(e) {
    showDialog(
      context: context,
      builder: (BuildContext context) {
        return AlertDialog(
          title: const Text('提示'),
          content: Text(e),
          actions: [
            TextButton(
              child: const Text('确定'),
              onPressed: () {
                Navigator.of(context).pop(); // 关闭对话框
              },
            ),
          ],
        );
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: () {
        FocusScopeNode currentFocus = FocusScope.of(context);
        if (!currentFocus.hasPrimaryFocus &&
            currentFocus.focusedChild != null) {
          currentFocus.focusedChild?.unfocus();
        }
      },
      child: Scaffold(
          appBar: AppBar(
            title: const Text(
              '地址设置',
              style: TextStyle(fontSize: 15),
            ),
            centerTitle: true,
            backgroundColor: Colors.amber,
          ),
          body: Padding(
            padding: const EdgeInsets.all(16.0),
            child: FormBuilder(
                key: _formKey,
                child: Center(
                  child: Column(
                    mainAxisSize: MainAxisSize.min,
                    children: [
                      FormBuilderTextField(
                          name: 'ip',
                          decoration: const InputDecoration(labelText: 'IP地址')),
                      const SizedBox(height: 12),
                      FormBuilderTextField(
                          name: 'port',
                          decoration: const InputDecoration(labelText: '端口号')),
                      const SizedBox(height: 12),
                      ElevatedButton(
                          onPressed: () {
                            if (_formKey.currentState!.saveAndValidate()) {
                              var formData = _formKey.currentState!.value;
                              String ip = formData['ip'] as String;
                              String port = formData['port'] as String;
                              _prefs.setString('ip', ip);
                              _prefs.setString('port', port);
                              fetchData(ip, port);
                              Navigator.pushReplacement(
                                  context,
                                  MaterialPageRoute(
                                      builder: (context) =>
                                          MyView(port: port, ip: ip)));
                            }
                          },
                          child: const Text('确定'))
                    ],
                  ),
                )),
          )),
    );
  }
}
